package com.eve.chatsocket.okhttp3;

import com.eve.chatsocket.entity.EventVo;

import com.eve.chatsocket.entity.ResponseData;
import com.eve.chatsocket.event.MessageEvent;
import com.eve.chatsocket.utils.WebSocketManager;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import static com.eve.chatsocket.constn.ChatConst.json;
@Component
@Slf4j
public class OkhttpListener extends WebSocketListener {
    @Autowired
    private ApplicationContext applicationContext;
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);;
        log.info("链接成功");
    }

    //重写onmessage

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        super.onMessage(webSocket, text);
        ResponseData responseData = json.fromJson(text,ResponseData.class);
        String sessionId = WebSocketManager.getUserSessionId(webSocket);
        EventVo vo = EventVo.builder().message(responseData).sessionId(sessionId).build();
        MessageEvent event = new MessageEvent(vo);
        applicationContext.publishEvent(event);
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        System.out.println(response);
    }
}
